package com.mifengs.mall.ui.hxcec;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.Conversation;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.Message;
import com.hyphenate.chat.OfficialAccount;
import com.hyphenate.helpdesk.easeui.util.IntentBuilder;
import com.hyphenate.helpdesk.easeui.util.SmileUtils;
import com.hyphenate.helpdesk.model.MessageHelper;
import com.hyphenate.util.DateUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.mall.ui.msg.MsgCenterActivity;
import com.mifengs.mall.util.UIUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lynn on 2017/11/17.
 */

public class ConversationListActivity extends BaseFragment {
    @BindView(R.id.ll_myMsg)
    LinearLayout mLlMyMsg;
    @BindView(R.id.ll_systemMsg)
    LinearLayout mLlSystemMsg;
    @BindView(R.id.ll_ssalesPromotionMsg)
    LinearLayout mLlSsalesPromotionMsg;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.v_top)
    View mVTop;
    private ConversationAdapter adapter;
    private final List<Conversation> conversationList = new ArrayList<>();
    private View view;

    public static ConversationListActivity newInstance() {
        ConversationListActivity fragment = new ConversationListActivity();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_em_conversation, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        mTvTitle.setText("消息");
        ListView mListView = (ListView) view.findViewById(R.id.listview);
        mListView.setAdapter(adapter = new ConversationAdapter(getContext(), 1, conversationList));
        loadConversationList();
        adapter.notifyDataSetChanged();
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Conversation conversation = (Conversation) parent.getItemAtPosition(position);
                // 进入主页面
                Intent intent = new IntentBuilder(getContext())
                        .setTargetClass(ChatActivity.class)
//                        .setVisitorInfo(DemoMessageHelper.createVisitorInfo())
                        .setServiceIMNumber(conversation.conversationId())
                        .setTitleName(Constant.HX_CUSTOMER_NAME)
                        .setShowUserNick(true)
                        .build();
                startActivity(intent);

            }
        });
        setStatusBarHeight();
    }

    private void setStatusBarHeight() {
        int statusHeight = UIUtil.getStatusHight();
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mVTop.getLayoutParams();
        layoutParams.setMargins(0, statusHeight, 0, 0);
    }

    @OnClick({R.id.ll_myMsg, R.id.ll_systemMsg, R.id.ll_ssalesPromotionMsg})
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            default:
                break;
            case R.id.ll_myMsg:
                intent = new Intent(getContext(), MsgCenterActivity.class);
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
            case R.id.ll_systemMsg:
                intent = new Intent(getContext(), MsgCenterActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.ll_ssalesPromotionMsg:
                intent = new Intent(getContext(), MsgCenterActivity.class);
                intent.putExtra("type", 2);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    class ConversationAdapter extends ArrayAdapter<Conversation> {

        ConversationAdapter(Context context, int resource, List<Conversation> objects) {
            super(context, resource, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.em_row_conversation, null);
                viewHolder = new ViewHolder();
                viewHolder.ivAvatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
                viewHolder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.tvTime = (TextView) convertView.findViewById(R.id.tv_time);
                viewHolder.tvMessage = (TextView) convertView.findViewById(R.id.tv_message);
                viewHolder.tvUnreadCount = (TextView) convertView.findViewById(R.id.tv_unread);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            Conversation conversation = getItem(position);
            if (conversation == null) {
                return convertView;
            }
            if (conversation.unreadMessagesCount() > 0) {
                viewHolder.tvUnreadCount.setVisibility(View.VISIBLE);
                viewHolder.tvUnreadCount.setText(String.valueOf(conversation.unreadMessagesCount()));
            } else {
                viewHolder.tvUnreadCount.setVisibility(View.GONE);
            }
            Message lastMessage = conversation.getLastMessage();

            if (lastMessage != null) {
                if (lastMessage.getType() == Message.Type.TXT) {
                    viewHolder.tvMessage.setText(SmileUtils.getSmiledText(getContext(), getTextMessageTitle(lastMessage)));
                } else if (lastMessage.getType() == Message.Type.VOICE) {
                    viewHolder.tvMessage.setText(R.string.message_type_voice);
                } else if (lastMessage.getType() == Message.Type.VIDEO) {
                    viewHolder.tvMessage.setText(R.string.message_type_video);
                } else if (lastMessage.getType() == Message.Type.LOCATION) {
                    viewHolder.tvMessage.setText(R.string.message_type_location);
                } else if (lastMessage.getType() == Message.Type.FILE) {
                    viewHolder.tvMessage.setText(R.string.message_type_file);
                } else if (lastMessage.getType() == Message.Type.IMAGE) {
                    viewHolder.tvMessage.setText(R.string.message_type_image);
                }
                viewHolder.tvTime.setText(DateUtils.getTimestampString(new Date(lastMessage.messageTime())));

            } else {
                viewHolder.tvMessage.setText("");
            }
            OfficialAccount officialAccount = conversation.officialAccount();
            if (officialAccount == null) {
                return convertView;
            }
            viewHolder.tvName.setText(Constant.HX_CUSTOMER_NAME);
            String imgUrl = officialAccount.getImg();
            if (imgUrl != null && imgUrl.startsWith("//")) {
                imgUrl = "http:" + imgUrl;
            }
            Glide.with(getContext()).load(imgUrl).error(R.drawable.hd_default_avatar).transform(new GlideCircleTransform(getContext())).into(viewHolder.ivAvatar);
            return convertView;
        }

        class ViewHolder {
            ImageView ivAvatar;
            TextView tvName;
            TextView tvTime;
            TextView tvMessage;
            TextView tvUnreadCount;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    public void refresh() {
        loadConversationList();
        adapter.notifyDataSetChanged();

    }

    private void loadConversationList() {
        Hashtable<String, Conversation> allConversations =
                ChatClient.getInstance().chatManager().getAllConversations();
        synchronized (conversationList) {
            conversationList.clear();
            for (String conversationId : allConversations.keySet()) {
                Conversation item = allConversations.get(conversationId);
                if (item.officialAccount() != null) {
                    conversationList.add(item);
                }
            }
        }
    }

    public String getTextMessageTitle(Message message) {
        switch (MessageHelper.getMessageExtType(message)) {
            case EvaluationMsg:
                return getString(R.string.message_type_eval_request);
            case OrderMsg:
                return getString(R.string.message_type_order_info);
            case TrackMsg:
                return getString(R.string.message_type_visitor_track);
            case FormMsg:
                return getString(R.string.message_type_form);
            case ArticlesMsg:
                return getString(R.string.message_type_articles);
            case RobotMenuMsg:
                return getString(R.string.message_type_robot);
            case ToCustomServiceMsg:
                return getString(R.string.message_type_tocs);
            case CustomEmojiMsg:
                return getString(R.string.message_type_custom_emoji);
        }

        EMTextMessageBody body = (EMTextMessageBody) message.body();
        return body.getMessage();
    }

//    protected void initNavigationBar() {
//        RelativeLayout llNavBar = (RelativeLayout)view.findViewById(R.id.navigation_bar);
//        if (llNavBar != null) {
//            LinearLayout llBack = (LinearLayout) view.findViewById(R.id.ll_back);
//            llBack.setVisibility(View.VISIBLE);
//            TextView titleText = (TextView) view.findViewById(R.id.tv_title);
//            titleText.setVisibility(View.VISIBLE);
////            titleText.setText("消息中心");
//            llBack.setVisibility(View.GONE);
//            llBack.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    finish();
//                }
//            });
//        }
//    }

}
